angular.module('mychat2').factory('server', ['$cacheFactory', '$q', '$http', 'socket',function($cacheFactory, $q, $http, socket) {
	console.log('server');
	var cache = window.cache = $cacheFactory('mychat');
	socket.on('mychat',function(result){
		console.log(result.action);
		console.log(result.data);
		switch(result.action){
			case 'getRoom':
			var data = result.data;
			if(data.roomId){
				angular.extend(cache.get(data.roomId),data);
				console.log(cache.get(data.roomId));
			}else{
				data.rooms.forEach(function(room){
					cache.get('rooms').push(room);
				});
			}
			break;

			case 'createRoom':
			var data = result.data;
			cache.get('rooms').push(data.room);
			break;

			case 'joinRoom':
			var data =result.data;
			var user = data.user;
			var roomId = data.roomId;
			if(!cache.get(roomId)){
				cache.get('rooms').forEach(function(room){
					if(room._id === roomId){
						cache.put(roomId,room);
					}
				});
			}
			cache.get(roomId).users.push(user);
			break;

			case 'leaveRoom':
			var userId = result.data.userId;
			var roomId = result.data.roomId;
			cache.get(roomId).users = cache.get(roomId).users.filter(function(user){
				return user._id !== userId; 
			});
			cache.get('rooms')&&cache.get('rooms').forEach(function(room){
				if(roomId === room._id){
					room.users.filter(function(user){
						return user._id !== userId;
					});
				}
			});

			case 'createMessage':
			var message = result.data;
			console.log('lalala');
		    cache.get(message._roomId).messages.push(message);
		    break;
		}
	});
	socket.on('err',function(data){
		console.log(data);
	});
	return{
		'validate':function(){
			var deffered = $q.defer();
			$http({
				url:'/api/validate',
				method:'GET'
			}).success(function(user){
				angular.extend(cache.get('user'),user);
				deffered.resolve();
			}).error(function(err){
				deffered.reject();
			});
			return deffered.promise;
		},
		'login':function(email){
			var deffered = $q.defer();
			$http({
				url:'/api/login',
				method:'post',
				data:{
					email:email
				}
			}).success(function(user){
				angular.extend(cache.get('user'),user);
				deffered.resolve();
			}).error(function(err){
				deffered.reject();
			});
			return deffered.promise;
		},
		'logout':function(){
			var deffered = $q.defer();
			$http({
				url:'/api/logout',
				method:'get',
				data:{
					'_userId':cache.get('user')._id
				}
			}).success(function(){
				var user = cache.get('user')
		        for (key in user) {
		          if (user.hasOwnProperty(key)) {
		            delete user[key]
		          }
		        }
				deffered.resolve();
			}).error(function(err){
				deffered.reject();
			});
			console.log(cache.get('rooms'));
			return deffered.promise;
		},
		'getUser': function(){
			if(!cache.get('user')){
				cache.put('user',{});
			}
			return cache.get('user');
		},
		'createRoom':function(roomName){
			console.log('client '+roomName);
			socket.emit('mychat',{
				'action':'createRoom',
				'params':{
					'roomName':roomName
				}
			});
		},
		'joinRoom':function(roomId){
			console.log('joinRoom');

			socket.emit('mychat',{
				'action':'joinRoom',
				'params':{
					'roomId':roomId,
					'userId':cache.get('user')._id					
				}
			});
		},
		'getAllRooms':function(){
			console.log('getAllRoom');
			console.log(cache.get('rooms'))
			if(!cache.get('rooms')){
				cache.put('rooms',[]);
				socket.emit('mychat',{
					'action':'getRoom'
				});
			}
			return cache.get('rooms');
		},
		'getRoom':function(roomId){
			if(!cache.get('roomId')){
				cache.put(roomId,{});
				socket.emit('mychat',{
					'action':'getRoom',
					'params':{
						'roomId':roomId
					}
				});
			}
			return cache.get(roomId);
		},
	    leaveRoom: function(leave) {
	      socket.emit('mychat', {
	        'action': 'leaveRoom',
	        'params': {
	        	'leave':leave
	        }
	      });
	    },
	    createMessage: function(message){
	    	console.log(message);
	    	socket.emit('mychat',{
	    		'action':'createMessage',
	    		'params':{
	    			'message':message
	    		}
	    	});
	    }
	}
}]);